//
//  AppDelegate.m
//  mskt
//
//  Created by 孔晓寅 on 15/12/23.
//  Copyright © 2015年 Suzhou fish Information Technology Co., Ltd. All rights reserved.
//

#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "MemberCenterViewController.h"
#import "FirstViewController.h"
#import "Reachability.h"
#import "ReachabViewController.h"

#import "WebViewController.h"

#import <PgySDK/PgyManager.h>
#import <PgyUpdate/PgyUpdateManager.h>
#import "BPush.h"

#import "LoginViewController.h"

#import "AppLaunchBannerViewController.h"




@interface AppDelegate ()<UIAlertViewDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
#pragma 正式发布时需要去除
//    //启动基本SDK
//    [[PgyManager sharedPgyManager] setEnableFeedback:NO];
//    [[PgyManager sharedPgyManager] startManagerWithAppId:@"1e6d4c05b2dc2ed9a6a746cabfd95bf2"];
//    //启动更新检查SDK
//    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:@"1e6d4c05b2dc2ed9a6a746cabfd95bf2"];
//    [[PgyUpdateManager sharedPgyManager] checkUpdate];
    
    [MobClick startWithAppkey:UmengMobClickkey reportPolicy:BATCH   channelId:@"iOS"];
    //设置友盟社会化组件appkey
    [UMSocialData setAppKey:UmengAppkey];
    
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    
 
//    NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//    [HttpNetWorkUtil addSkipBackupAttributeToItemAtPath:documentsDirectory];
    
    [self event_isloginok];
  
    
    [_window makeKeyAndVisible];
    [self customizeInterface];
    
   [AppLaunchBannerViewController show];
    
    //自定义返回按钮
    UIImage *backButtonImage = [UIImage imageNamed:@"fanhui_2x"];

    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    //将返回按钮的文字position设置不在屏幕上显示
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    [UIBarButtonItem appearance];
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    

    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:@"" pushMode:BPushModeDevelopment withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:YES];

    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {

        [BPush handleNotification:userInfo];
    }

    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
 
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
 
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - Methods

- (void)setupViewControllers {

   /*
    UIViewController *firstViewController = [[FirstViewController alloc] init];
    UIViewController *firstNavigationController = [[UINavigationController alloc]
                                                   initWithRootViewController:firstViewController];
    */
    
    UINavigationController *indexNavigationController = [[UIStoryboard storyboardWithName:@"Index" bundle:nil]  instantiateInitialViewController];
    
    WebViewController *secondViewController = [[WebViewController alloc] initWithUrl:@"http://sz114.wcwifi.cn/zjsz/pos_toShop.do" withTitle:@"商城"];

    UIViewController *secondNavigationController = [[UINavigationController alloc]
                                                    initWithRootViewController:secondViewController];
    
//    WebViewController *thirdViewController = [[WebViewController alloc] initWithUrl:@"http://202.102.86.228:9080/today" withTitle:@"今天"];
  
     WebViewController *thirdViewController = [[WebViewController alloc] initWithUrl:@"http://58.211.5.134:8080/today" withTitle:@"今天"];
    
    
    
    UIViewController *thirdNavigationController = [[UINavigationController alloc]
                                                   initWithRootViewController:thirdViewController];
    
    UIViewController *fourthViewController = [[MemberCenterViewController alloc] init];
    UIViewController *fourthNavigationController = [[UINavigationController alloc]
                                                    initWithRootViewController:fourthViewController];
    
    
    
    
    RDVTabBarController *tabBarController = [[RDVTabBarController alloc] init];
    [tabBarController setViewControllers:@[indexNavigationController, secondNavigationController,
                                           thirdNavigationController,fourthNavigationController]];
    self.viewController = tabBarController;
    
    [self customizeTabBarForController:tabBarController];
}

- (void)customizeTabBarForController:(RDVTabBarController *)tabBarController {
    UIImage *finishedImage = [UIImage imageNamed:@"tabbar_selected_background"];
    UIImage *unfinishedImage = [UIImage imageNamed:@"tabbar_normal_background"];
    NSArray *tabBarItemImages = @[@"first", @"second", @"third",@"fourth"];
    NSArray *tabBarItemTitles = @[@"我的苏州", @"商城", @"今天", @"我的"];
    
    NSInteger index = 0;
    for (RDVTabBarItem *item in [[tabBarController tabBar] items]) {
        [item setBackgroundSelectedImage:finishedImage withUnselectedImage:unfinishedImage];
        UIImage *selectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_selected",
                                                      [tabBarItemImages objectAtIndex:index]]];
        UIImage *unselectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_normal",
                                                        [tabBarItemImages objectAtIndex:index]]];
        [item setFinishedSelectedImage:selectedimage withFinishedUnselectedImage:unselectedimage];
        [item setTitle:[tabBarItemTitles objectAtIndex:index ]];
        [item setSelectedTitleAttributes:@{
                                           UITextAttributeFont: [UIFont systemFontOfSize:12],
                                           UITextAttributeTextColor: [utils getButtonColor],
                                           }];
        [item setUnselectedTitleAttributes:@{
                                             UITextAttributeFont: [UIFont systemFontOfSize:12],
                                             UITextAttributeTextColor: [UIColor grayColor],
                                             }];
        index++;
    }
}

- (void)customizeInterface {
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    
    UIImage *backgroundImage = nil;
    NSDictionary *textAttributes = nil;
    
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        backgroundImage = [UIImage imageNamed:@"navigationbar_background_tall"];
        
        textAttributes = @{
                           NSFontAttributeName: [UIFont boldSystemFontOfSize:18],
                           NSForegroundColorAttributeName: [UIColor whiteColor],
                           };
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        backgroundImage = [UIImage imageNamed:@"navigationbar_background"];
        
        textAttributes = @{
                           UITextAttributeFont: [UIFont boldSystemFontOfSize:18],
                           UITextAttributeTextColor: [UIColor whiteColor],
                           UITextAttributeTextShadowColor: [UIColor clearColor],
                           UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetZero],
                           };
#endif
    }
    
    //    [navigationBarAppearance setBackgroundImage:backgroundImage
    //                                  forBarMetrics:UIBarMetricsDefault];
    //    [navigationBarAppearance setTitleTextAttributes:textAttributes];
}

-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn1 = [Reachability reachabilityForInternetConnection];
    
    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
        NSLog(@"有wifi");
        isExistenceNetwork = YES;
        
    } else if ([conn1 currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
        NSLog(@"使用手机自带网络进行上网");
        isExistenceNetwork = YES;
    } else { // 没有网络
        
        NSLog(@"没有网络");
        isExistenceNetwork = NO;
    }
    
    //    if (!isExistenceNetwork) {
    //
    //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
    //                                                        message:@"当前网络不可用，请检查当前网络。"
    //                                                       delegate:self
    //                                              cancelButtonTitle:@"OK"
    //                                              otherButtonTitles:nil,nil];
    //        [alert show];
    //    }
    
    return isExistenceNetwork;
}

- (BOOL)event_checkNetworkState
{
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn1 = [Reachability reachabilityForInternetConnection];
    
    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
        NSLog(@"有wifi");
        return YES;
        
    } else if ([conn1 currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
        NSLog(@"使用手机自带网络进行上网");
        return YES;
    } else { // 没有网络
        
        NSLog(@"没有网络");
        return NO;
    }
}

-(void)event_beginWithNetworkOK
{
    [self setupViewControllers];
    [self.window setRootViewController:self.viewController];
}

-(void)event_beginWithNetworkErr
{
    ReachabViewController *XNN_VC  = [[ReachabViewController alloc]init];
    self.window.rootViewController = XNN_VC;
}

- (void)event_networkStateChange:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    [self event_checkNetworkState];
    if (status == NotReachable) {
        [self event_beginWithNetworkErr];
    }
}

-(void)showviewcontroller{
    if([self event_checkNetworkState]){
        [self event_beginWithNetworkOK];
    }else{
        ReachabViewController *XNN_VC  = [[ReachabViewController alloc]init];
        self.window.rootViewController = XNN_VC;
    }
}

-(void)event_isloginok{
    //重新绑定channelID
    NSString *channelId = [utils getString:CHANNELID];
    
    if (channelId) {
        [self BindChannelID:channelId];
    }
    
    [self setupViewControllers];
    self.window.rootViewController = self.viewController;
}

-(void)event_gotologin:(NSString *)msg
{
    //重新解绑channelID
    NSString *channelId = [utils getString:CHANNELID];
    if (channelId) {
        [self BindChannelID:@""];
    }
    [utils setObject:nil forkey:PERSONINFO];
    [utils setString:nil forkey:TOKEN];
    
    //    UIViewController *view = [[LoginViewController alloc] init];
    //    UIViewController *loginNavigationController = [[UINavigationController alloc]
    //                                                   initWithRootViewController:view];
    //
    //    [self.window setRootViewController:loginNavigationController];
    LoginViewController *view = [[LoginViewController alloc]init];
    RDVTabBarController *tab = (RDVTabBarController *)self.viewController;
    UINavigationController *nav = (UINavigationController *) tab.selectedViewController;
    [[nav rdv_tabBarController] setTabBarHidden:YES animated:YES];
    [nav pushViewController:view animated:YES];
    
    //    if (msg) {
    //        [OMGToast showWithText:msg  bottomOffset:50 duration:2.0];
    //    }
}

- (void)testLocalNotifi
{
    NSLog(@"测试本地通知啦！！！");
    NSDate *fireDate = [[NSDate new] dateByAddingTimeInterval:5];
    [BPush localNotification:fireDate alertBody:@"这是本地通知" badge:3 withFirstAction:@"打开" withSecondAction:@"关闭" userInfo:nil soundName:nil region:nil regionTriggersOnce:YES category:nil];
}

// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    // 打印到日志 textView 中
    NSLog(@"********** iOS7.0之后 background **********");
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else//杀死状态下，直接跳转到跳转页面。
    {
    }
    
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
        if (result) {
            NSString *channelId = [BPush getChannelId];
            NSString *channelId_loc = [utils getString:CHANNELID];
            
            if (channelId && ![channelId isEqualToString:channelId_loc]) {
                [utils setString:channelId forkey:CHANNELID];
                [self BindChannelID:channelId];
            }
            
            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    NSLog(@"设置tag成功");
                }
            }];
        }
        
    }];
    
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // App 收到推送的通知
    [BPush handleNotification:userInfo];
    NSLog(@"********** ios7.0之前 **********");
    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        NSLog(@"acitve or background");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    else//杀死状态下，直接跳转到跳转页面。
    {
    }
    
    NSLog(@"%@",userInfo);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"接收本地通知啦！！！");
    [BPush showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    //在该方法中，回调信息拼接在url中：
    //1.支付成功：url＝scheme://resulted=00&result=成功&ORDERSEQ=订单号&ORDERAMOUNT＝订单金额   、
    //2.支付失败： url＝scheme://resulted=01&result=失败
    //3.支付取消：url＝scheme://resulted=02&result=取消
    NSString* params =[url absoluteString];
    if ([params hasPrefix:@"bestPaySuzhou://"]){
        
        NSDictionary *dict = @{@"result":params};
        [[NSNotificationCenter defaultCenter] postNotificationName:REQUEST_PAYRESULT object:REQUEST_PAYRESULT userInfo:dict];
        
    }else{
        return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
    }
    
    return YES;
}

-(void)BindChannelID:(NSString *)channelid{
    
    NSString *token = [utils getString:TOKEN];
    if (token && ![token isEqualToString:@""]) {
        
        [HttpNetWorkUtil requestupdateChannel:@{@"channelId":channelid,@"devType":@"4"} success:^(id json) {
        } fail:^{
        }];
    }
}

@end
